package org.streets.eis.ext.analysis.pages;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.util.MapModel;
import org.apache.wicket.util.resource.IStringResourceStream;
import org.apache.wicket.util.resource.PackageResourceStream;
import org.apache.wicket.velocity.markup.html.VelocityPanel;
import org.streets.database.Limits;
import org.streets.eis.ext.analysis.QuerySet;
import org.streets.eis.ext.analysis.entities.QueryStruct;
import org.streets.eis.util.Pager;

/**
 * 
 * 1.显示查询下拉列表；
 * 2.用户选择一个查询后，点击执行按钮；系统查询数据，并显示数据;
 * 
 * 
 */
public class ExecQueryPage extends QueryPage {
	private IStringResourceStream template = new PackageResourceStream(BuildQueryPage.class,"queryresults.vm");
	private IModel<Map<String,VelocityModel>> templateContext;

	private VelocityModel vm = new VelocityModel();
	private Pager pager = new Pager(0);
	
    final WebMarkupContainer panelResult = new WebMarkupContainer("panelResult");
	final WebMarkupContainer panelOP = new WebMarkupContainer("panelOP");

	public ExecQueryPage(QueryStruct query) {
		this();
		this.currentQuery = query;
	}

	public ExecQueryPage() {
		super();

		Map<String, VelocityModel> map = new HashMap<String, VelocityModel>();
		map.put("result",vm);
		templateContext =  new MapModel<String, VelocityModel>(map);

		
		Form form = new Form("form");
		add(form);
		panelResult.setOutputMarkupId(true);
		panelOP.setOutputMarkupId(true);
		panelResult.setVisible(false);
		panelResult.setOutputMarkupPlaceholderTag(true);
		form.add(panelOP);
		form.add(panelResult);

        IModel<List<QueryStruct>> queries = getQueriesModel();
		//下拉列表的值绑定到了页面的currentQuery属性，随着选择值的不同，currentQuery也应跟着变
        final DropDownChoice<QueryStruct> ddcQueryList = new DropDownChoice<QueryStruct>("ddl_querylist", new PropertyModel<QueryStruct>(ExecQueryPage.this,"currentQuery"), queries,new ChoiceRenderer("name"));
		panelOP.add(ddcQueryList);
		AjaxFormComponentUpdatingBehavior behavior = new AjaxFormComponentUpdatingBehavior("onchange") {
			private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target) {
				templateContext.getObject().remove("result");
				target.addComponent(panelResult);
				target.addComponent(panelOP);
	        }
        };
        ddcQueryList.add(behavior);

		//新建按钮
		AjaxFallbackLink<Object> linkNewQuery =new AjaxFallbackLink<Object>("linkNewQuery"){
				private static final long serialVersionUID = 1L;
				@Override
				public void onClick(AjaxRequestTarget target) {
					QueryStruct query = new QueryStruct();
					query.setName("新建查询的名称");
					query.setMemo("新建查询的描述");
					query.setTableExpr("");
					query.setConditionExpr("");
                	setResponsePage(new BuildQueryPage(query));
				}
		};
		panelOP.add(linkNewQuery);
		
        //修改查询按钮
		AjaxFallbackLink<Object> linkEditQuery = new AjaxFallbackLink<Object>("linkEditQuery") {
		    	private static final long serialVersionUID = 1L;
				@Override
				public boolean isEnabled(){
					return currentQuery != null; 
				}

		    	@Override
				public void onClick(AjaxRequestTarget target) {
					if (currentQuery != null) {
	                	setResponsePage(new BuildQueryPage(currentQuery));
	                }else{
	                	showInfo("请选择一个查询！");
	                }
	            }		    	
			};
		panelOP.add(linkEditQuery);

		//删除查询按钮
	    AjaxFallbackLink<Object> linkDeleteQuery = new AjaxFallbackLink<Object>("linkDelQuery") {
				private static final long serialVersionUID = 1L;

				@Override
				public boolean isEnabled(){
					return currentQuery != null; 
				}

				@Override
				public void onClick(AjaxRequestTarget target) {
					if (currentQuery != null) {
		                //getMessageBox().confirm(content, callback);
						builder.delete(currentQuery);
		                if (target != null) {
							target.addComponent(ddcQueryList);
							target.addComponent(panelResult);
		                }		            
					}else{
		                showInfo("请选择一个查询！");
		            }
		                
	            }
	        };
		panelOP.add(linkDeleteQuery);
	        
		//执行查询按钮
		AjaxFallbackLink<Object> linkExecQuery = new AjaxFallbackLink<Object>("linkExecQuery") {
				private static final long serialVersionUID = 1L;
				@Override
				public boolean isEnabled(){
					return currentQuery != null; 
				}
				
				@Override
				public void onClick(AjaxRequestTarget target) {
	                	if (currentQuery != null) {
	                		pager.first();

	                		Limits limit = Limits.of(pager.getStartRow(), pager.getPageSize());
	                		QuerySet qs = queryService.query(user, currentQuery, limit);
	                		vm.fill(qs);
	                		
	                		templateContext.getObject().remove("result");//修改model里的数据
	            			templateContext.getObject().put("result",vm);
	            			if (target != null) {
	            				panelResult.setVisible(true);
	            				target.addComponent(panelResult);
	            			}
						} else {
							showInfo("请选择一个查询！");
						}
	            }
	        };
		panelOP.add(linkExecQuery);

            
		// 添加模板
	    VelocityPanel vp = new VelocityPanel("templatePanel", templateContext){
				private static final long serialVersionUID = 1L;
				@Override
				protected IStringResourceStream getTemplateResource()
				{
					return template;
				}
			};
		panelResult.add(vp);

		// 添加分页
		panelResult.add(new Label("lblPageCount",new PropertyModel(pager,"msg")));
		panelResult.add(new PagerAjaxLink("linkPageFirst","first"));
		panelResult.add(new PagerAjaxLink("linkPagePrevious","previous"));
		panelResult.add(new PagerAjaxLink("linkPageNext","next"));
		panelResult.add(new PagerAjaxLink("linkPageEnd","last"));
		
		// 导出excel
    	DownloadLink linkExportExcel = new DownloadLink("linkExportExcel",
    			new LoadableDetachableModel<File>(){
					private static final long serialVersionUID = 1L;
					@Override
					public File load() {
						try {
							return builder.exportExcel(currentQuery);
						}
						catch (SQLException e) {
							showError("导出错误："+e.getMessage());
							e.printStackTrace();
							return null;
						}
						catch (IOException e) {
							showError("导出错误："+e.getMessage());
							e.printStackTrace();
							return null;
						}
				
					}	
    			}){
					
    		private static final long serialVersionUID = 1L;
			@Override
    		public boolean isEnabled(){
    			return vm.getRows().size() > 0;  
    		}
    	};
    	
		linkExportExcel.setDeleteAfterDownload(true);
        panelResult.add(linkExportExcel);
		
	}
	
	
	private class PagerAjaxLink extends AjaxFallbackLink<Object>{
	
		private static final long serialVersionUID = 1L;
		private String op;
		public PagerAjaxLink(String id,String op) {
			super(id);
			this.op=op;
		}

		@Override
		public boolean isEnabled(){
			if (op.equalsIgnoreCase("first")){	
				return pager.getCurrentPage() != 1;
			}
			if (op.equalsIgnoreCase("previous")){	
				return pager.getCurrentPage() != 1;
			}
			if (op.equalsIgnoreCase("next")){	
				return (pager.getCurrentPage() != pager.getTotalPages()) &&(pager.getTotalPages() != 0 );
			}
			if (op.equalsIgnoreCase("last")){	
				return (pager.getCurrentPage() != pager.getTotalPages())&&(pager.getTotalPages() != 0 );
			}
			
			return true;
			
		}
		
		@Override
		public void onClick(AjaxRequestTarget target) {
			if (op.equalsIgnoreCase("first")){	
				pager.first();
			}
			if (op.equalsIgnoreCase("previous")){	
				pager.previous();
			}
			if (op.equalsIgnoreCase("next")){	
				pager.next();
			}
			if (op.equalsIgnoreCase("last")){	
				pager.last();
			}
			
			if (currentQuery != null) {
    			
        		Limits limit = Limits.of(pager.getStartRow(), pager.getPageSize());
        		QuerySet qs = queryService.query(user, currentQuery, limit);
        		vm.fill(qs);
    			
    			templateContext.getObject().remove("result");//修改model里的数据
    			templateContext.getObject().put("result",vm);
        		target.addComponent(panelResult);
			}else{
				showInfo("请选择一个查询！");
			}
		}
					  
	  }

}


	
    

	


